package loginServer;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import mainController.ServerController;
import databaseController.DatabaseController;


public class LoginServer extends Thread {
	
	private ServerSocket serverSocket;
	private ServerController serverController;
	
	public LoginServer(ServerController serverController) {
		this.serverController = serverController;
		this.createServer(8000);
	}
	
	private void createServer(int port) {
		this.serverSocket = null;
		
		try {
		    this.serverSocket = new ServerSocket(port);
		}
		catch (IOException e) {
		    System.err.println("LoginServer:: Could not listen on port: " + port);
		    System.exit(1);
		}
	}	
	
	@Override
	public void run() {
		while (true) {
	        try {
	        	Socket socket = this.serverSocket.accept();
	        	//LoginServer.this.serverController.createClient(socket);
	        	Handshake t = new Handshake(socket);
	        	t.start();
	        }
	        catch (IOException e) {
	            System.err.println("LoginServer:: Accept failed.");
	        }
		}
	}
	
	public ServerSocket getServerSocket() {
		return this.serverSocket;
	}
	
	class Handshake extends Thread {
		
		private Socket clientSocket;
		private ObjectOutputStream bufferOut;
		private ObjectInputStream bufferIn;
		
		public Handshake(Socket clientSocket) {
			this.clientSocket = clientSocket;
			try {
				this.bufferOut = new ObjectOutputStream(this.clientSocket.getOutputStream());
				this.bufferIn = new ObjectInputStream(this.clientSocket.getInputStream());
			}
			catch (IOException e) {
				System.err.println("LoginServer::" + e);
			}
		}
		
		@Override
		public void run() {
			while (true) {
				String message = null;
				try {
					message = (String) this.bufferIn.readObject();
					if (message == null) {
						continue;
					}
					if (DatabaseController.getInstance().hasSensor(message)) {
		            	LoginServer.this.serverController.createClient(message, this.bufferOut, this.bufferIn);
		            }
					else {
						System.err.println("LoginTask:: Couldn't find sensor: " + message);
						this.bufferOut.writeObject("wrong_code");
					}
					return;
				}
				catch (IOException e) {
					System.err.println("LoginTask:: Couldn't read from buffer");
					return;
				}
				catch (ClassNotFoundException e) {
					System.err.println(e);
				}
			}
		}
	}
}
